package com.sfzd5.exam;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ShowLogActivity extends AppCompatActivity {

    Button bt_clean;
    ListView lv;

    List<String> logs = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_log);

        lv = findViewById(R.id.lv);
        bt_clean = findViewById(R.id.bt_clean);

        String CacheDiaPath = getCacheDir().toString();
        File file = new File(CacheDiaPath + "/log.txt");

        if(file.exists()){
            FileReader reader = null;
            BufferedReader bufferedReader = null;
            try {
                reader = new FileReader(file);
                bufferedReader = new BufferedReader(reader);
                String str = "";
                StringBuffer sb = new StringBuffer();
                while((str = bufferedReader.readLine()) != null) {
                    if(str.equals("<TimberLog>")){
                        sb.delete( 0, sb.length() );
                    } else if(str.equals("</TimberLog>")){
                        logs.add(sb.toString());
                    } else {
                        sb.append(str).append("\n");
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        lv.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                logs));

        bt_clean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String CacheDiaPath = getCacheDir().toString();
                File file = new File(CacheDiaPath + "/log.txt");
                if(file.exists()){
                    file.delete();
                }
            }
        });
    }
}